package com.itheima.travel.service.impl;

import com.itheima.travel.dao.RouteMapper;
import com.itheima.travel.pojo.Route;
import com.itheima.travel.service.RouteService;
import com.itheima.travel.utils.MybatisUtils;
import com.itheima.travel.utils.PageBean;
import com.itheima.travel.utils.PageUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RouteServiceImpl implements RouteService {
    @Override
    public PageBean<Route> findRouteByPage(int pageSize, int pageNumber, String cid) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        RouteMapper mapper = sqlSession.getMapper(RouteMapper.class);
        //1.查询满足条件的总条数
        int totalCount = mapper.findTotalCount(cid);
        //2.创建PageBean对象
        PageBean<Route> pb = new PageBean<Route>(pageSize,totalCount);
        //3.封装PageNumber的值
        pb.setPageNumber(pageNumber);
        //4.查询当前页面的数据信息
        //4.1 计算起始索引
        int startIndex = (pageNumber-1)*pageSize;
        //4.2调用方法,查询数据信息
        List<Route> routeList= mapper.findRouteByPage(startIndex,pageSize,cid);
        //4.3将查询结果封装到pb中
        pb.setData(routeList);

        //5.计算前5后4
        int[] ints = PageUtils.pagination(pageNumber, pb.getTotalPage());
        pb.setStart(ints[0]);
        pb.setEnd(ints[1]);

        // 关闭sqlSession
        MybatisUtils.closeSession(sqlSession);
        //返回pb
        return pb;
    }
}
